import React, { Component, useState, useEffect, Fragment } from 'react';
import axios from 'axios';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Button,
  Table,
  Icon,
  Divider,
  Popconfirm,
  Spin,
  Form,
  Modal,
  Input,
  InputNumber,
  Radio,
  Select,
  DatePicker,
  message,
  Upload,
  Card,
  Tag,
} from 'antd';
import { router } from 'umi';
import { connect } from 'dva';
function getToken() {
  const token = localStorage.getItem('business-token');
  return token;
}
import moment from 'moment';
import { getParam } from '@/utils/utils';
let TheEditorList = Form.create()(props => {
  const [scope, setScope] = useState('');
  const [productVisible, setproductVisible] = useState(false);
  const [list, setlist] = useState([]);
  const [Modaltotal, settotal] = useState(0);
  const [selectedRowKeys, setselectedRowKeys] = useState([]);
  const [goodslist, setgoodslist] = useState([]);
  const [goodslists, setgoodslists] = useState([]);
  const [fileList, setfileList] = useState(null);
  const [FromExcel, setFromExcel] = useState([]);
  const [Conditions, setConditions] = useState(null);
  const [current, setcurrent] = useState({});
  const [rangeValues, setrangeValues] = useState([]);
  const [phones, setphones] = useState([]);
  const [keyWord, setkeyWord] = useState(false);
  const [SelectAllSopt, setSelectAllSopt] = useState([]);
  const [tags, setTags] = useState([]);
  const [selecthand, setSelecthand] = useState([]);
  const FormItem = Form.Item;
  const RadioGroup = Radio.Group;
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const { Search } = Input;
  const {
    form: { getFieldDecorator, getFieldValue, validateFields },
    isFormModal,
    loading,
    handleSubmit,
    onCancel,
  } = props;
  useEffect(() => {
    props.dispatch({
      type: 'coupons/getUpdatePageData',
      payload: { id: getParam('id') },
      callback: res => {
        setcurrent(res.data);
        setrangeValues(res.data.rangeValues);
        setphones(res.data.phones);
        setTags(res.data.rangeList);
        setScope(res.data.rangeType);
      },
    });
  }, []);
  const onSear = e => {
    setkeyWord(true);
    axios(`/hzsx/index/ableProductV1?keyWord=${e}&pageNumber=1&pageSize=10`, {
      method: 'get',
      headers: { token: getToken() },
    }).then(res => {
      if (res) {
        setkeyWord(false);
        message.success('查询成功！');
        console.log(res, 'reas');
        if (res && res.data && res.data.data && res.data.data.records) {
          setSelectAllSopt(res.data.data.records);
        } else {
          setSelectAllSopt([]);
        }
      } else {
        message.error(res.data.msg);
      }
    });
  };
  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 5 },
      md: { span: 5 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
      md: { span: 17 },
    },
  };
  const onSelecthandleChange = e => {
    setSelecthand(e);
  };
  const onTj = () => {
    selecthand.map(item => JSON.parse(item));
    let selecthandArr = [];
    for (let i = 0; i < selecthand.length; i++) {
      selecthandArr.push(JSON.parse(selecthand[i]));
    }
    let arr = tags.concat(selecthandArr);
    var result = [];
    var obj = {};
    for (var i = 0; i < arr.length; i++) {
      if (!obj[arr[i].productId]) {
        result.push(arr[i]);
        obj[arr[i].productId] = true;
      }
    }
    props.form.setFieldsValue({ userRange11: result });
    setTags(result);
  };
  const onQk = () => {
    props.form.setFieldsValue({ userRange11: [] });
    setTags([]);
  };
  const handleSubmits = e => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        props.dispatch({
          type: 'coupons/upDate',
          payload: {
            id: current.id,
            num: values.num,
            userLimitNum: values.userLimitNum === 0 ? values.num : values.userLimitNum,
            status: values.status,
          },
        });
      }
    });
  };
  const onThes = e => {
    setScope(e.target.value);
    if (scope === '') {
      setgoodslist([]);
      setgoodslists([]);
      setselectedRowKeys([]);
    }
  };
  const validatorGeographic = (rule, value, callback) => {
    if (value.length === 0) {
      callback('请选择指定商品!');
      return;
    }
    callback();
  };
  const columns = [
    {
      title: 'id',
      dataIndex: 'value',
    },
    {
      title: '名字',
      dataIndex: 'description',
    },
  ];
  console.log(scope, 'scope');
  return (
    <PageHeaderWrapper title="修改优惠券">
      <Card>
        <Spin spinning={false}>
          <Form onSubmit={handleSubmits}>
            <FormItem {...formItemLayout} label="优惠券类别" required>
              {getFieldDecorator('scene', {
                rules: [{ required: true, message: '请选择优惠券' }],
                initialValue: current.scene,
              })(
                <Select>
                  <Option value={'RENT'}>租赁</Option>
                  <Option value={'BUY_OUT'}>买断</Option>
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="标题" required>
              {getFieldDecorator('title', {
                rules: [{ required: true, message: '请输入标题' }],
                initialValue: current.title,
              })(<Input placeholder="请输入标题" />)}
            </FormItem>
            <FormItem {...formItemLayout} label="发放总量" required>
              {getFieldDecorator('num', {
                rules: [{ required: true, message: '请输入发放总量' }],
                initialValue: current.num,
              })(<InputNumber placeholder="请输入发放总量" style={{ width: '90%' }} />)}
              &nbsp;张
            </FormItem>
            <FormItem {...formItemLayout} label="面额" required>
              {getFieldDecorator('discountAmount', {
                rules: [{ required: true, message: '请输入面额' }],
                initialValue: current.discountAmount,
              })(<InputNumber placeholder="请输入面额" style={{ width: '90%' }} />)}
              &nbsp;元
            </FormItem>
            <FormItem {...formItemLayout} label="使用条件" required>
              {getFieldDecorator('minAmount', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: current.minAmount === 0 ? '0' : '1',
              })(
                <RadioGroup>
                  <Radio value="0">不限制</Radio>
                  <Radio value="1">
                    满&nbsp;
                    {getFieldDecorator('minPurchase', {
                      initialValue: current.minAmount,
                    })(
                      <InputNumber
                        min={0}
                        precision={2}
                        // ={getFieldValue('minAmount') === '0'}
                      />,
                    )}
                    &nbsp;元
                  </Radio>
                </RadioGroup>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} required label="每人限领">
              {getFieldDecorator('userLimitNum', {
                initialValue: current.userLimitNum,
              })(
                <Select>
                  <Option value={0}>无限制</Option>
                  <Option value={1}>1张</Option>
                  <Option value={2}>2张</Option>
                  <Option value={3}>3张</Option>
                  <Option value={4}>4张</Option>
                  <Option value={5}>5张</Option>
                  <Option value={6}>6张</Option>
                  <Option value={7}>7张</Option>
                  <Option value={8}>8张</Option>
                  <Option value={9}>9张</Option>
                  <Option value={10}>10张</Option>
                </Select>,
              )}
            </FormItem>
            
            <FormItem {...formItemLayout} required label="时间设置">
              {getFieldDecorator('type', {
                initialValue: current.delayDayNum === null ? 0 : 1,
              })(
                <RadioGroup>
                  <Radio value={0}>按固定时间</Radio>
                  <Radio value={1}>按领取日期</Radio>
                </RadioGroup>,
              )}
            </FormItem>
            
            <FormItem {...formItemLayout} colon={false} label=" ">
              {getFieldValue('type') === 0 ? (
                getFieldDecorator('startEnd', {
                  initialValue: current && [moment(current.startTime), moment(current.endTime)],
                })(<RangePicker />)
              ) : (
                <div>
                  自领取时{' '}
                  {getFieldDecorator('delayDayNum', {
                    rules: [{ required: true, message: '请输入天数' }],
                    initialValue: current.delayDayNum,
                  })(<InputNumber min={1} precision={0} />)}{' '}
                  天内未使用优惠券自动过期
                </div>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券使用人群" required>
              {getFieldDecorator('userRange', {
                rules: [{ required: true, message: '请选择使用条件' }],
                initialValue: current.phones !== null ? 'PART' : current.forNew,
              })(
                <RadioGroup>
                  <Radio value="F">所有人</Radio>
                  <Radio value="PART">指定用户</Radio>
                  <Radio value="T">新用户</Radio>
                </RadioGroup>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券适用范围" required>
              <RadioGroup defaultValue={scope} onChange={onThes}>
                <Radio value="">全场通用</Radio>
                <Radio value="CATEGORY">指定类目</Radio>
                <Radio value="PRODUCT">指定商品</Radio>
              </RadioGroup>
            </FormItem>
            {scope === 'PRODUCT' ? (
              <FormItem {...formItemLayout} label="指定商品" required>
                {getFieldDecorator('userRange11', {
                  rules: [
                    {
                      validator: validatorGeographic,
                    },
                  ],
                  initialValue: tags,
                })(
                  <Fragment>
                    <Spin spinning={keyWord}>
                      <div style={{ background: '#ECECEC', padding: '30px' }}>
                        <div style={{ display: 'flex' }}>
                          <Search
                            placeholder="商品名称/货号"
                            onSearch={onSear}
                            style={{ width: 200 }}
                          />
                          <Select
                            mode="multiple"
                            style={{ width: '100%' }}
                            placeholder="请选择商品"
                            onChange={onSelecthandleChange}
                            style={{ width: 300, marginLeft: 20 }}
                          >
                            {SelectAllSopt.map((item, value) => {
                              return (
                                <Option key={`${JSON.stringify(item)}`}>
                                  {' '}
                                  {item.name && item.productName}
                                </Option>
                              );
                            })}
                          </Select>
                          <Button
                            type="primary"
                            style={{
                              margin: '0 20px',
                            }}
                            onClick={onTj}
                          >
                            新增
                          </Button>
                          <Button onClick={onQk}>清空</Button>
                        </div>
                        <div
                          style={{
                            fontSize: 12,
                            fontFamily: 'PingFangSC-Regular,PingFang SC',
                            fontWeight: 400,
                            color: 'rgba(0,0,0,0.25)',
                          }}
                        >
                          购买以下分类商品可使用优惠券抵扣金额，已选中
                          <span
                            style={{
                              color: '#000',
                              fontWeight: 700,
                            }}
                          >
                            {tags.length}
                          </span>
                          个分类
                        </div>
                        <div>
                          {tags.map((tag, index) => {
                            return (
                              <Tag key={index} closable onClose={() => handleClose(tag)}>
                                {tag && tag.description}
                              </Tag>
                            );
                          })}
                        </div>
                      </div>
                    </Spin>
                  </Fragment>,
                )}
              </FormItem>
            ) : null}
            {scope === 'CATEGORY' ? (
              <FormItem {...formItemLayout} label="指定类目" required>
                <Table
                  rowKey="id"
                  bordered
                  columns={columns}
                  dataSource={rangeValues}
                  pagination={false}
                />
              </FormItem>
            ) : null}
            <FormItem {...formItemLayout} label="优惠券状态" required>
              {getFieldDecorator('status', {
                rules: [{ required: true, message: '请选择' }],
                initialValue: current.status,
              })(
                <RadioGroup>
                  <Radio value="VALID">有效</Radio>
                  <Radio value="INVALID">无效</Radio>
                  <Radio value="RUN_OUT">已用完</Radio>
                </RadioGroup>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="优惠券展示说明">
              {getFieldDecorator('displayNote', {
                initialValue: current.displayNote,
              })(<Input.TextArea placeholder="最多显示12个字" />)}
            </FormItem>
            <div style={{ textAlign: 'center' }}>
              <Button
                onClick={() => router.go(-1)}
                style={{ width: 120, height: 40, marginRight: 20 }}
              >
                返回
              </Button>
              <Button type="primary" htmlType="submit" style={{ width: 120, height: 40 }}>
                确定
              </Button>
            </div>
          </Form>
        </Spin>
      </Card>
    </PageHeaderWrapper>
  );
});
export default connect(({ coupons, loading }) => ({ ...coupons, loading: loading.models.coupons }))(
  TheEditorList,
);
